package com.xiaomi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaomi.domain.User;
import com.xiaomi.service.UserService;
import com.xiaomi.util.JsonResult;
import com.xiaomi.util.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author： YongZ
 * @date： 2024/5/29
 * @description：
 * @modifiedBy：
 */
@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    private boolean isUserValid(User user) {
        return user.getUsername() != null && user.getPassword() != null;
    }

    @PostMapping("/register")
    public JsonResult register(@RequestBody User user) {
        if (!isUserValid(user)) {
            log.error("非法操作,请传入正确的参数");
            return JsonResult.fail("非法操作,请传入正确的参数");
        }

        List<User> list = userService.list();
        for (User existingUser : list) {
            if (existingUser.getUsername().equalsIgnoreCase(user.getUsername())) {
                log.error("非法操作,用户名已存在");
                return JsonResult.fail("抱歉,用户名已存在");
            }
        }
        // 将password进行md5加密
        try {
            user.setPassword(Util.encrypt(user.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        boolean isSuccess = userService.save(user);
        return JsonResult.success(isSuccess ? "注册成功" : "未知错误,注册失败");
    }


    /**
     * 登录 成功后返回状态码和token
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public JsonResult login(@RequestBody User user) throws NoSuchAlgorithmException {
        if (!isUserValid(user)) {
            return JsonResult.fail("非法操作,请传入正确的参数");
        }
        // 用传进来的name比对数据库的name
        User existingUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()).last("limit 1"));
        if (existingUser == null) {
            log.error("非法操作,用户名不存在");
            return JsonResult.fail("抱歉,用户名不存在");
        } else if (!existingUser.getPassword().equals(Util.encrypt(user.getPassword()))) {
            log.error("非法操作,密码错误");
            return JsonResult.fail("抱歉,密码错误");
        }

        return JsonResult.success("登录成功!");
    }
}
